package com.zzyl.nursing.service.member.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.mapper.member.MemberReservationMapper;
import com.zzyl.nursing.service.member.IMemberReservationService;
import com.zzyl.nursing.vo.ReservationCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 预约信息业务实现
 * @author zbr
 * @version 1.0
 * @since 2025/3/5 21:19
 */
@Service
public class MemberReservationServiceImpl extends ServiceImpl<MemberReservationMapper, Reservation> implements IMemberReservationService {

    @Autowired
    private MemberReservationMapper memberReservationMapper;

    /**
     * 查询每个时间段剩余预约次数
     *
     * @param time
     * @return
     */
    @Override
    public List<ReservationCountVo> getCountByTime(Long time) {
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        return memberReservationMapper.getCountByTime(startTime, endTime);
    }

    /**
     * 查询取消预约数量
     *
     * @param userId
     * @return
     */
    @Override
    public Integer getCancelledReservationCount(Long userId) {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        return memberReservationMapper.getCancelledReservationCount(userId, startTime, endTime).size();
    }

    /**
     * 新增预约
     * @param dto
     */
    @Override
    public void saveReservation(ReservationDto dto) {
        Reservation one = lambdaQuery().eq(Reservation::getMobile, dto.getMobile())
                .eq(Reservation::getTime, dto.getTime()).one();
        if (ObjUtil.isNotNull(one)) {
            throw new RuntimeException("该手机号此时段已预约");
        }
        Reservation reservation = BeanUtil.toBean(dto, Reservation.class);
        reservation.setStatus(0);
        reservation.setCreateBy(UserThreadLocal.get().toString());
        reservation.setCreateTime(DateTime.now());
        save(reservation);
    }

    /**
     * 分页查询预约信息
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public TableDataInfo<Reservation> getPage(Integer pageNum, Integer pageSize, Integer status) {
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(status), Reservation::getStatus, status);
        queryWrapper.eq(Reservation::getCreateBy, UserThreadLocal.get().toString());
        IPage<Reservation> page = Page.of(pageNum, pageSize);

        page(page, queryWrapper);

        TableDataInfo<Reservation> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    /**
     * 取消预约
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Reservation reservation = new Reservation();
        reservation.setId(id);
        reservation.setStatus(2);
        reservation.setUpdateBy(UserThreadLocal.get().toString());
        if (!updateById(reservation)) {
            throw new BaseException("取消预约失败");
        }
    }

    /**
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReservationStatus() {
        List<Reservation> list = lambdaQuery().eq(Reservation::getStatus, 0)
                .le(Reservation::getTime, LocalDateTime.now())
                .list();

        list.forEach(v -> v.setStatus(3));

        if (!updateBatchById(list)) {
            throw new BaseException("更新预约状态失败");
        }
    }
}
